package org.arestaurant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

public class Foods extends Activity{
    public static String CATEGORY_ID_SELECTED = "";
    public static int CATEGORY_ID_INDEX = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!ConnectionServices.checkHttpConnection()) {
            Intent intent = new Intent(this, Setting.class);
            startActivity(intent);
        } else {
            setContentView(R.layout.foods);
            Spinner spinner = (Spinner) findViewById(R.id.categorySpinner);
            final JSONArray categoryList = FoodServices.getCategoryList();
            String[] categoryStr = new String[categoryList.length()+1];
            categoryStr[0] = "All";
            for (int index = 0; index < categoryList.length(); index++) {
                try {
                    JSONObject category =  categoryList.getJSONObject(index);
                    categoryStr[index+1] = category.getString("categoryName");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            ArrayAdapter<String> catetoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryStr);
            catetoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(catetoryAdapter);
            spinner.setSelection(CATEGORY_ID_INDEX);
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                    try {
                        String cat1 = CATEGORY_ID_SELECTED.toLowerCase();
                        String cat2;
                        if(arg2 == 0) {
                        	cat2 = "";
                        } else {
                        	cat2 = categoryList.getJSONObject(arg2-1).getString("productCategoryId").toLowerCase();
                        }
                        if (!cat1.equals(cat2)) {
                        	if (arg2 == 0) { 
                        		CATEGORY_ID_SELECTED = "";
                        	} else {
                        		CATEGORY_ID_SELECTED = categoryList.getJSONObject(arg2-1).getString("productCategoryId");
                        	}
                        	CATEGORY_ID_INDEX = arg2;
                            selectCategory();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub
                }
            });
            JSONArray productList = FoodServices.getFoodList();
            try {
                SimpleListView foodListView = new SimpleListView(this);
                for (int count = 0; count < productList.length(); count++) {
                    final JSONObject food = productList.getJSONObject(count);
                    String foodDetail = food.getString("productId")+ " - " + food.getString("internalName");
                    final TextView textView = new TextView(this);
                    textView.setText(foodDetail);
                    textView.setTextColor(Color.BLACK);
                    textView.setTextSize(14);
                    textView.setPadding(0, 5, 0, 5);
                    textView.setId(count);
                    final int bgColor;
                    if (count%2 == 0) {
                        bgColor = Color.rgb(200, 200, 200);
                    } else {
                        bgColor = Color.rgb(180, 180, 180);
                    }
                    textView.setBackgroundColor(bgColor);
                    textView.setOnLongClickListener(new OnLongClickListener() {
                        public boolean onLongClick(View arg0) {
                            try {
                                Food.FOOD_ID_SELECTED = food.getString("productId");
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            openProductPopup(textView);
                            return false;
                        }
                    });
                    foodListView.addView(textView, null, true);
                    ConnectionServices.disconnect();
                }
                foodListView.setTranslationY(50);
                addContentView(foodListView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    private void openProduct() {
        Intent intent = new Intent(this, Food.class);
        startActivity(intent);
    }
    private void selectCategory() {
        finish();
        Intent intent = new Intent(this, Foods.class);
        startActivity(intent);
    }
    private void openProductPopup(View view) {
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.food_popup, null);
        final PopupWindow pw = new PopupWindow(layout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);
        Button detailBtn = (Button)layout.findViewById(R.id.productDetail);
        detailBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                // close the popup
                pw.dismiss();
                openProduct();
            }
        });
        Button orderBtn = (Button)layout.findViewById(R.id.productOrder);
        orderBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                // close the popup
                pw.dismiss();
            }
        });
        pw.showAtLocation(view, Gravity.CENTER, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.foods_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.foodsSearch:
            return true;
        default:
            return true;
        }
    }
}
